package cn.com.cpic.insurance.rulecheck.core;

import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 一个简单实现的可修改Map
 * 
 * @author 代波
 * @since 2011-8-13
 * @param <K> Map中key的类型
 * @param <V> Map中value的类型
 */
public final class SimpleModifiableMap<K, V extends Tokenable<K>> implements ModifiableMap<K, V> {
	private static final long serialVersionUID = 4246156532088672279L;

	private final Map<K, V> map;

	public SimpleModifiableMap() {
		this(null);
	}

	public SimpleModifiableMap(Set<V> set) {
		super();
		this.map = Collections.synchronizedMap(new HashMap<K, V>());
		if (set != null) {
			for (V v : set) {
				map.put(v.getToken(), v);
			}
		}
	}

	public boolean contains(V c) {
		return map.containsValue(c);
	}

	public boolean add(V c) {
		if (map.containsKey(c.getToken())) {
			return false;
		} else {
			map.put(c.getToken(), c);
			return true;
		}
	}

	public boolean remove(V c) {
		return map.remove(c.getToken()) != null;
	}

	public int size() {
		return map.size();
	}

	public boolean isEmpty() {
		return map.isEmpty();
	}

	public Iterator<V> iterator() {
		return new HashSet<V>(map.values()).iterator();
	}

	public boolean containsKey(K key) {
		return map.containsKey(key);
	}

	public Iterator<K> keyIterator() {
		return new HashSet<K>(map.keySet()).iterator();
	}

	public V get(K key) {
		return map.get(key);
	}
}
